package org.bai.meetingfilm.backend.user.controller;

import com.google.common.collect.Maps;
import org.bai.meetingfilm.backend.user.controller.vo.LoginReqVO;
import org.bai.meetingfilm.backend.user.service.UserServiceAPI;
import org.bai.meetingfilm.common.vo.BaseResponseVO;
import org.bai.meetingfilm.exception.CommonServiceException;
import org.bai.meetingfilm.util.JwtTokenUtil;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Map;

@RestController
@RequestMapping(value = "/user")
public class UserController {

    @Resource
    private UserServiceAPI userServiceAPI;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public BaseResponseVO<Map<String, String>> login(@RequestBody LoginReqVO loginReqVO) throws CommonServiceException {
        loginReqVO.checkParam();

        String userId = userServiceAPI.checkUserLogin(loginReqVO.getUserName(), loginReqVO.getPassword());

        JwtTokenUtil instance = JwtTokenUtil.instance();
        String randomKey = instance.getRandomKey();
        String token = instance.generateToken(userId, randomKey);

        Map<String, String> result = Maps.newHashMap();
        result.put("randomKey", randomKey);
        result.put("token", token);

        return BaseResponseVO.success(result);
    }
}
